import request from "@/common/request"
import { Message } from "element-ui"

export default class TextCorrection {
	constructor() {
		this.title = "文本纠错"
		this.tag = "button"
		this.errorMessage = ""
		this.errorCode = ""
	}

	// 点击菜单时触发的函数
	async exec(editor) {
		if (this.errorCode == 9000) {
			Message.error(this.errorMessage)
			return
		}
		const text = editor.getText()

		if (!text) {
			return
		}

		const rootDom = editor.getEditableContainer()
		const linesRoot = rootDom.querySelector(".w-e-scroll>div")
		const lines = linesRoot.children

		editor.emit("startLoading")
		try {
			const { code, data, msg } = await request("post", "/bindapi/textCorrection", {
				text: text.replace(/\n|\r/g, " "),
			})
			this.errorCode = code
			if (code != 0) {
				throw new Error(msg)
			}

			const { errors, source, target } = data[0]
			const regex = /[^a-zA-Z0-9\u4e00-\u9fa5]/g

			if (errors && errors.length) {
				for (let i = 0; i < errors.length; i++) {
					const [trueText, falseText, index] = errors[i]
					if (trueText.length != 1) {
						continue
					}

					let threshold = index
					let dir = -1
					errors[i][3] = []

					for (;;) {
						if (regex.test(text[threshold]) || threshold < 0 || threshold > text.length) {
							if (dir == -1) {
								dir *= -1
								threshold = index
							} else {
								break
							}
						}
						errors[i][3][threshold] = text[threshold]
						threshold += dir
					}
				}
			}

			const errorslist = []
			let textLength = 0

			for (let i = 0; i < lines.length; i++) {
				const element = lines[i]
				const textContent = element.textContent
				textLength += textContent.length

				if (textContent) {
					for (let j = 0; j < errors.length; j++) {
						const content = errors[j][3].join("")

						if (textContent.indexOf(content) != -1) {
							errorslist.push({
								...errors[j],
								2: textLength - textContent.length + errors[j][2],
								element,
								content,
								line: i,
								position: errors[j][2],
							})
							break
						}
					}
				}
			}

			editor.emit("errorslist", errorslist)
			editor.emit("endLoading")
		} catch (error) {
			editor.emit("errorslist", [])
			editor.emit("endLoading", error.message)
			Message.error(error.message)
			this.errorMessage = error.message
		}
	}

	// 获取菜单执行时的 value ，用不到则返回空 字符串或 false
	getValue() {
		return false
	}

	// 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
	isActive() {
		return false
	}

	// 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
	isDisabled() {
		if (this.errorCode == 9000) {
			return true
		}
		return false
	}
}
